<!DOCTYPE html>
<html>
<head>
    <title>B/S架构-RSA前端加密后端解密示例</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
    <form id="form1">
        <!--public_key是多行字符串，若浏览器无法使用ES6标准，可以使用隐藏表单获取public_key。-->
        <input type="hidden" name="pubkey" id="pubkey" value="{{ pubkey }}" />
        username: <input id="username" name="username" type="text" value="admin"></input><br/>
        password: <input id="password" name="password" type="password" value="admin"></input><br/>
        <input id="submit" type="button" value="submit"/><br/>
    </form>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jsencrypt/3.0.0-rc.1/jsencrypt.min.js"></script>
    <script type="text/javascript">
        "use strict";
        function RSAEncrypt(string) {
            var encrypt = new JSEncrypt();
            //对应hidden input，浏览器不支持ES6时，删除此函数倒数第二行，取消下面两行注释
            //var pubkey = $('#pubkey').val()
            //encrypt.setPublicKey(pubkey);
            encrypt.setPublicKey(`{{ pubkey }}`);
            return encrypt.encrypt(string);
        }
        $('#submit').click(function () {
            var username = $('#username').val();
            var password = $('#password').val();
            $.ajax({
                url: "{{ url_for('index') }}",
                type: 'post',
                data: {username: username, password: RSAEncrypt(password)},
                dataType: 'json',
                success: function (res) {
                    console.info(res);
                    if (res.code===0) {
                        alert("服务端解密成功，password解密结果是：" + res.password);
                    } else {
                        alert(res.msg);
                    }
                },
                error: function (xhr) {
                    alert('出错了');
                }
            });
        });
    </script>
</body>
</html>